import random
import uuid
from http import HTTPStatus
from dashscope import Generation  # 建议dashscope SDK 的版本 >= 1.14.0
from django.shortcuts import get_object_or_404
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, ListAPIView, RetrieveAPIView
from rest_framework.response import Response
import requests
from .models import *
from .ser import *

messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]


# 单论对话
class DialogueView(APIView):
    def post(self, request):
        question = request.data.get('question')

        messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                    {'role': 'user', 'content': question}]
        response = Generation.call(model="qwen-turbo",
                                   messages=messages,
                                   # 设置随机数种子seed，如果没有设置，则随机数种子默认为1234
                                   seed=random.randint(1, 10000),
                                   # 将输出设置为"message"格式
                                   result_format='message')
        if response.status_code == HTTPStatus.OK:
            print(response)
            print(response['output']['choices'][0]['message']['content'])
            resmes = response['output']['choices'][0]['message']['content']
        else:
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code,
                response.code, response.message
            ))
            resmes = response.message

        return Response({"code": 200, 'mes': resmes})


# 实现多轮对话
class ConversationView(APIView):
    def post(self, request):
        user_input = request.data['user_input']  # 调用函数获取用户输入
        if user_input == 'exit':  # 假设输入'exit'则退出对话
            return Response({"code": 10010, 'message': '对话结束'})
        messages.append({'role': 'user', 'content': user_input})

        response = Generation.call(model="qwen-turbo",
                                   messages=messages,
                                   result_format='message')

        if response.status_code == HTTPStatus.OK:
            print(response.output.choices[0]['message']['content'])  # 直接打印回复内容
            messages.append({'role': 'assistant',  # 假设这里我们假设回复的role是'assistant'
                             'content': response.output.choices[0]['message']['content']})
            return Response({"code": 200, 'message': response.output.choices[0]['message']['content']})
        else:
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code,
                response.code, response.message
            ))


# 模拟实时数据API视图(chart)
class DataView(APIView):
    def get(self, request):
        # 生成模拟的实时数据
        data = [random.randint(100, 300) for _ in range(7)]
        return Response({'seriesData': data})


# 假设的全局变量，用于存储对话历史
messages = []

# 通义千问API的URL和API密钥
from rest_framework import status


class QianwenView(APIView):
    def post(self, request):
        user_input = request.data.get('user_input')  # 获取用户输入
        if user_input == 'exit':  # 假设输入'exit'则退出对话
            return Response({"code": 10010, 'message': '对话结束'})

        # 添加用户消息
        messages.append({'role': 'user', 'content': user_input})

        # 调用通义千问API
        response = self.call_qwen_api(user_input, messages)

        if response.status_code == HTTPStatus.OK:
            assistant_message = response.json()['choices'][0]['message']['content']
            messages.append({'role': 'assistant', 'content': assistant_message})
            return Response({"code": 200, 'message': assistant_message})
        else:
            error_message = f'Request id: {response.headers.get("X-Request-ID")}, ' \
                            f'Status code: {response.status_code}, ' \
                            f'Error code: {response.json().get("code")}, ' \
                            f'Error message: {response.json().get("message")}'
            print(error_message)
            return Response({"code": 500, 'message': 'Failed to get response from Qwen'})

    def call_qwen_api(self, user_input, messages):
        # 构建请求数据
        payload = {
            'model': 'qwen-turbo',
            'messages': messages,
            'result_format': 'message'
        }
        # 这里替换为你的API URL
        api_url = 'https://api.qwen.com/ask'

        # 发送请求
        return requests.post(api_url, json=payload)


# 起名大师
class GenerateNameView(APIView):
    def post(self, request):
        gender = request.data.get('gender')
        birthdate = request.data.get('birthdate')
        preferences = request.data.get('preferences')

        # 构建提示词
        prompt = f"根据以下信息为新生儿起一个合适的名字：\n性别: {gender}\n出生日期: {birthdate}\n喜好: {preferences}"

        # 调用通义千问API
        response = self.call_qwen_api(prompt)

        if response.status_code == status.HTTP_200_OK:
            generated_name = response.output.choices[0]['message']['content']
            return Response({"code": 200, 'message': generated_name}, status=status.HTTP_200_OK)
        else:
            error_message = f'Request id: {response.request_id}, ' \
                            f'Status code: {response.status_code}, ' \
                            f'Error code: {response.code}, ' \
                            f'Error message: {response.message}'
            print(error_message)
            return Response({"code": 500, 'message': 'Failed to get response from Qwen'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def call_qwen_api(self, prompt):
        # 构建请求数据
        payload = {
            'model': 'qwen-turbo',
            'messages': [{'role': 'user', 'content': prompt}],
            'result_format': 'message'
        }

        # 调用API
        return Generation.call(**payload)


# 获取商品列表
class GoodsListView(ListAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer


class GoodsdetailView(RetrieveAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'id'

class AddBrowseRecordView(APIView):
    def post(self, request, product_id):
        # 获取或生成用户标识
        user_id = request.session.get('user_id')
        if not user_id:
            user_id = str(uuid.uuid4())
            request.session['user_id'] = user_id

        good = get_object_or_404(Goods, pk=product_id)

        # 创建浏览记录
        browse_record = BrowseHistory.objects.create(user_id=user_id, product=good)

        serializer = BrowseHistorySerializer(browse_record)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

class RecommendGoodsView(APIView):
    def get(self, request, user_id):
        # 获取用户最近的5条浏览记录
        recent_browse_records = BrowseHistory.objects.filter(user_id=user_id).order_by('-add_time')[:5]

        # 提取这些浏览记录的特征
        features = [record.good.features for record in recent_browse_records]

        # 根据特征查询符合条件的商品
        recommended_goods_ids = Goods.objects.filter(features__in=features).values_list('id', flat=True)

        # 排除用户已经浏览过的商品
        browsed_goods_ids = BrowseHistory.objects.filter(user_id=user_id).values_list('product_id', flat=True)
        recommended_goods_ids = list(set(recommended_goods_ids) - set(browsed_goods_ids))

        # 按销量排序并返回推荐商品
        recommended_goods = Goods.objects.filter(id__in=recommended_goods_ids).order_by('-sales')

        serializer = GoodsSerializer(recommended_goods, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)